//
//  CIBNHomeController.m
//  CIBN
//
//  Created by ZNGOO on 16/7/18.
//  Copyright © 2016年 韦儒健. All rights reserved.
//

#import "CIBNHomeController.h"
#import "CIBNScrollMenuView.h"
#import "CIBNMenuListModel.h"
#import "CIBNBlockListModel.h"
#import "CIBNHomeListModel.h"
#import "CIBNHomeCell.h"
#import "CIBNHomePageScrollCell.h"
#import "CIBHomeListCell.h"
#import "CIBNPlayController.h"
#import "InterfacOrientation.h"
#import "CIBNHomeCategoryController.h"



static NSString * pageScrollCell = @"CIBNHomePageScrollCell";
static NSString * homeCell = @"CIBNHomeCell";
static NSString * homeListCell = @"CIBHomeListCell";

@interface CIBNHomeController ()<CIBNScrollMenuViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

/**  菜单*/
@property (nonatomic,strong) CIBNScrollMenuView * menuView;

/**  菜单数据 */
@property (nonatomic,strong) NSMutableArray * menuArray;

/**  集合视图 */
@property (nonatomic,strong) UICollectionView * collectionView;

/**  分类数据 */
@property (nonatomic,strong) NSMutableArray * blockArray;

/**  主页数据 */
@property (nonatomic,strong) NSMutableArray * homeArray;

/** 组头 */

@property (nonatomic,strong) UILabel * headlabel;
@end

@implementation CIBNHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self loadMenuData];
    
    [self loadHomeData];
    
    [self createMenu];
    
    [self createCollection];
}

#pragma mark - 创建CollectionView
- (void)createCollection{
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame), ScreenWidth, ScreenHeight - CGRectGetMaxY(self.menuView.frame) - 49)
                                             collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[CIBNHomeCell class] forCellWithReuseIdentifier:homeCell];
    [self.collectionView registerClass:[CIBNHomePageScrollCell class] forCellWithReuseIdentifier:pageScrollCell];
    [self.collectionView registerClass:[CIBHomeListCell class] forCellWithReuseIdentifier:homeListCell];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headCell"];
    [self.view addSubview:self.collectionView];
    
    self.headlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 30)];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadHomeData];
    }];
    
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:case 1:
        {
            return CGSizeMake(0, 0);
        }
            break;
            
        default:
        {
            
            return CGSizeMake(ScreenWidth, 40);
        }
            break;
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    switch (section) {
        case 0:
        {
            return UIEdgeInsetsMake(10, 0, 10, 0);
        }
            break;
            
        default:
        {
            return UIEdgeInsetsMake(10, 5, 0, 5);
        }
            break;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0: case 1:
        {
            return nil;
        }
            break;
            
        default:
        {
            UICollectionReusableView * view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headCell" forIndexPath:indexPath];
            view.backgroundColor = [UIColor groupTableViewBackgroundColor];
            
            CIBNBlockListModel * model = self.blockArray[indexPath.section];
            
            self.headlabel.text = model.Name;
            self.headlabel.backgroundColor = [UIColor whiteColor];
            [view addSubview:self.headlabel];
            
            return view;
        }
            break;
    }
}


#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.blockArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    switch (section) {
        case 0:
        {
            return 1;
        }
            break;
            
        default:
        {
            
            return [self loadSectionNum:section];
        }
            break;
    }
    

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            return CGSizeMake(ScreenWidth, ScreenWidth * 9 / 16);
        }
            break;
            
        default:{
            
            if ([self loadSectionNum:indexPath.section] == 4) {
               return CGSizeMake((ScreenWidth - 30) /2, (((ScreenWidth - 30) /2) * 9 /16) + 40);
            }
            else{
                return CGSizeMake((ScreenWidth - 40) /3, (((ScreenWidth - 40) /3) * 16/9) + 20);
            }
            
            
        }
            break;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
 
    switch (indexPath.section) {
        case 0:
        {
            // 1. 滚动图
            CIBNHomePageScrollCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:pageScrollCell forIndexPath:indexPath];
            [cell setScrollViewImageArr:[self loadScrollViewArr:indexPath.section]];
            
            cell.pushPlayVCBlock = ^(CIBNHomeListModel * model){
                CIBNPlayController * playVC = [[CIBNPlayController alloc] init];
                playVC.model = model;
                [self.navigationController pushViewController:playVC animated:YES];
            };
            
            return cell;
        }
            break;
            
        default:
        {
            if ([self loadSectionNum:indexPath.section] == 4) {
                CIBNHomeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:homeCell forIndexPath:indexPath];
    
                CIBNHomeListModel * model = [self loadScrollViewArr:indexPath.section][indexPath.row];
                
                [cell setHomeCell:model];
                return cell;
            }
            else{
                CIBHomeListCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:homeListCell forIndexPath:indexPath];
                CIBNHomeListModel * model = [self loadScrollViewArr:indexPath.section][indexPath.row];
                [cell setHomeCell:model recomend:0];
                return cell;
            }
        }
            break;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld--%ld",indexPath.row,indexPath.section);
    
    CIBNHomeListModel * model = [self loadScrollViewArr:indexPath.section][indexPath.row];
    CIBNPlayController * playVC = [[CIBNPlayController alloc] init];
    playVC.model = model;
    [self.navigationController pushViewController:playVC animated:YES];
    
}

#pragma mark - 计算每组个数
- (NSUInteger)loadSectionNum:(NSUInteger)section{
    
    NSUInteger num = 0;
    for (int index = 0; index < self.homeArray.count; index++) {
        CIBNBlockListModel * model = self.blockArray[section];
        CIBNHomeListModel * homeModel = self.homeArray[index];
        
        if ([homeModel.blockid isEqualToString:model.BlockID]) {
            num++;
        }
    }
    
    if (num%2 != 0) {
        return num -1;
    }else{
        return num;
    }
}

#pragma mark - 计算每组的元素
- (NSMutableArray *)loadScrollViewArr:(NSUInteger)section{
    
    NSMutableArray * array = [[NSMutableArray alloc] init];
    for (int index = 0; index < self.homeArray.count; index++) {
        CIBNBlockListModel * model = self.blockArray[section];
        CIBNHomeListModel * homeModel = self.homeArray[index];
        
        if ([homeModel.blockid isEqualToString:model.BlockID]) {
            [array addObject:homeModel];
        }
    }
    
    return array;
}

#pragma mark - 创建菜单
- (void)createMenu{
    
    [self.leftBtn setImage:[UIImage imageNamed:@"logo"] forState:UIControlStateNormal];
    self.centerTitle.hidden = YES;
    
    self.menuView = [[CIBNScrollMenuView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, 30)];
    self.menuView.delegate = self;
    [self.view addSubview:self.menuView];
    
}

#pragma mark - 获取首页数据
- (void)loadHomeData{
    
    
    [MBProgressHUD bwm_showHUDAddedTo:self.view title:Loading];
    [RJNetwoking POST:Domain_URL body:@{
                                         @"Cmdid":@"4672",
                                         @"Seqid":@"3",
                                         @"ProtoVer":@"1",
                                         @"UID":@"3000000001",
                                         @"HID":@"049364046517234524AF2C911F6D5228",
                                         @"TID":@"42756",
                                         @"CliVer":@"72058693549555712",
                                         @"Oemid":@"10001",
                                         @"Epgid":@"9",
                                         @"Sessid":@"10411839877922554998",
                                         @"TermType":@"30",
                                         @"SubjectID":@"1543"
                                         } success:^(id  _Null_unspecified responseObject) {
                                             
                                             if ([responseObject[@"Status"] integerValue] == 0) {
                                                 
                                                 self.blockArray = [CIBNBlockListModel mj_objectArrayWithKeyValuesArray:responseObject[@"BlockList"]];
                                                 self.homeArray = [CIBNHomeListModel mj_objectArrayWithKeyValuesArray:responseObject[@"MenuList"]];
                                             }
                                             
                                             [self.collectionView reloadData];
                                             [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                                             [self.collectionView.mj_header endRefreshing];
        
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [MBProgressHUD bwm_showTitle:@"出错啦" toView:self.view hideAfter:2.0 msgType:BWMMBProgressHUDMsgTypeError];
    }];
}

#pragma mark - 获取菜单
- (void)loadMenuData{

    [RJNetwoking POST:Domain_URL body:@{@"Cmdid":@"4609",
                                       @"Seqid":@"319",
                                       @"ProtoVer":@"1",
                                       @"UID":@"3000000001",
                                       @"HID":@"049364046517234524AF2C911F6D5228",
                                       @"TID":@"42756",
                                       @"CliVer":@"72058693549555712",
                                       @"Oemid":@"10001",
                                       @"Epgid":@"9",
                                       @"Sessid":@"10411839877922554998",
                                       @"TermType":@"30",
                                       @"SubjectType":@"1"
                                       } success:^(id  _Null_unspecified responseObject) {

                                          self.menuArray = [CIBNMenuListModel mj_objectArrayWithKeyValuesArray:responseObject[@"GetMenuList"]];
                                           
                                           [self.menuView setItemsArray:self.menuArray];
                                           
                                       } failure:^(NSError * _Nonnull error) {
                                           [MBProgressHUD bwm_showTitle:@"出错啦" toView:self.view hideAfter:2.0 msgType:BWMMBProgressHUDMsgTypeError];
                                       }];
    
}
#pragma mark - CIBNScrollMenuViewDelegate
- (void)didSelectItemIndex:(NSUInteger)index{
    switch (index) {
        case 100:
        {
            self.tabBarController.selectedIndex = 1;
        }
            break;
        case 0:
        {
            
        }
            break;
        
        default:
        {
            NSMutableArray * arr = [[NSMutableArray alloc] init];
            for (CIBNMenuListModel * model in self.menuArray) {
                if (![model.Name isEqualToString:@"会员专区"]) {
                    [arr addObject:model];
                }
                
            }
            CIBNMenuListModel * model = arr[index];
            CIBNHomeCategoryController * categoryVC = [[CIBNHomeCategoryController alloc] init];
            categoryVC.model = model;
            categoryVC.isH = index;
            [self.navigationController pushViewController:categoryVC animated:YES];
        }
            break;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [InterfacOrientation setInterfacOrientation:UIInterfaceOrientationPortrait];
    self.tabBarController.tabBar.hidden = NO;
}
@end
